package com.blue;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

public class Main {
    public static void method01() throws IOException {
        // 获取 SqlSessionFactoryBuilder 对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 获取 SqlSessionFactory 对象
        ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml"); // 底层实际调用的是这个加载配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");      // 从类路径上加载资源
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        // 获取 SqlSession 对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 执行 SQL 语句
        int count = sqlSession.insert("insertCar");
        System.out.println("插入了几条数据: " + count);

        // 手动提交事务
        sqlSession.commit();
    }

    public static void method02() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession = factory.openSession(); // 开启会话
            //
            int count = sqlSession.insert("insertCar");
            System.out.println(count);
            sqlSession.commit();

        } catch (IOException e) {
            e.printStackTrace();
            if (sqlSession != null) {
                sqlSession.rollback();
            }

        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }

    }


    public static void main(String[] args) throws IOException {
        method01();
        method02();
    }
}
